<template>
  <el-dialog
      top="5vh"
      width="1400px"
      title="SKU批量管理"
      :visible.sync="dialogValue"
      :close-on-click-modal="false"
      append-to-body
  >
    <div class="sku-batch-container">
      <div class="product-info">
        <h3>{{ currentProduct.name }}</h3>
        <p>商品ID: {{ currentProduct.id }}</p>
      </div>
      
      <!-- 批量操作区域 -->
      <el-card class="batch-actions" shadow="never">
        <div slot="header" class="clearfix">
          <span>批量操作</span>
        </div>
        
        <el-row :gutter="20">
          <el-col :span="6">
            <el-input
              v-model="batchPrice"
              placeholder="批量设置价格"
              type="number"
              min="0"
              step="0.01"
            >
              <template slot="prepend">¥</template>
            </el-input>
          </el-col>
          <el-col :span="6">
            <el-input
              v-model="batchOriginalPrice"
              placeholder="批量设置原价"
              type="number"
              min="0"
              step="0.01"
            >
              <template slot="prepend">¥</template>
            </el-input>
          </el-col>
          <el-col :span="6">
            <el-input
              v-model="batchStock"
              placeholder="批量设置库存"
              type="number"
              min="0"
            />
          </el-col>
          <el-col :span="6">
            <el-button type="primary" @click="batchUpdate">批量更新</el-button>
          </el-col>
        </el-row>
        
        <el-row :gutter="20" style="margin-top: 15px;">
          <el-col :span="6">
            <el-input
              v-model="batchUnit"
              placeholder="批量设置单位"
            />
          </el-col>
          <el-col :span="6">
            <el-select v-model="batchStatus" placeholder="批量设置状态" style="width: 100%;">
              <el-option label="启用" :value="1"></el-option>
              <el-option label="禁用" :value="0"></el-option>
            </el-select>
          </el-col>
          <el-col :span="6">
            <el-button @click="selectAll">全选</el-button>
            <el-button @click="unselectAll">取消全选</el-button>
          </el-col>
          <el-col :span="6">
            <el-button type="danger" @click="batchDelete">批量删除</el-button>
          </el-col>
        </el-row>
      </el-card>
      
      <!-- SKU列表 -->
      <el-card class="sku-list" shadow="never">
        <div slot="header" class="clearfix">
          <span>SKU列表</span>
          <el-button style="float: right; padding: 3px 0" type="text" @click="refreshList">刷新</el-button>
        </div>
        
        <el-table
            size="large"
            stripe
            border
            v-loading="loading"
            :data="skuList"
            row-key="id"
            @selection-change="onSelectionChange"
            element-loading-spinner="el-icon-loading"
            element-loading-background="rgba(255, 255, 255, 0.8)"
        >
          <el-table-column type="selection" width="55"/>
          
          <el-table-column prop="sku_code" label="SKU编码" width="150"/>
          <el-table-column prop="image" label="SKU图片" width="120">
            <template slot-scope="scope">
              <el-image
                  :preview-src-list="[scope.row.image]"
                  style="width: 80px; height: 80px"
                  :src="scope.row.image" fit="contain">
                <template #error>
                  <img src="@/assets/file.png" alt="" style="width: 80px; height: 80px">
                </template>
              </el-image>
            </template>
          </el-table-column>
          <el-table-column prop="spec_combination" label="规格组合" min-width="200">
            <template slot-scope="scope">
              <div v-if="scope.row.spec_combination">
                <el-tag 
                  v-for="(value, key) in JSON.parse(scope.row.spec_combination)" 
                  :key="key"
                  size="mini"
                  style="margin-right: 5px; margin-bottom: 5px;"
                >
                  {{ key }}: {{ value }}
                </el-tag>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="price" label="价格" width="100">
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.price"
                size="mini"
                type="number"
                min="0"
                step="0.01"
                @blur="updateSku(scope.row)"
              />
            </template>
          </el-table-column>
          <el-table-column prop="original_price" label="原价" width="100">
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.original_price"
                size="mini"
                type="number"
                min="0"
                step="0.01"
                @blur="updateSku(scope.row)"
              />
            </template>
          </el-table-column>
          <el-table-column prop="stock" label="库存" width="100">
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.stock"
                size="mini"
                type="number"
                min="0"
                @blur="updateSku(scope.row)"
              />
            </template>
          </el-table-column>
          <el-table-column prop="unit" label="单位" width="80">
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.unit"
                size="mini"
                @blur="updateSku(scope.row)"
              />
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="100">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.status"
                :active-value="1"
                :inactive-value="0"
                @change="updateSku(scope.row)"
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" fixed="right" width="120">
            <template slot-scope="scope">
              <el-button type="text" @click="editSku(scope.row)">编辑</el-button>
              <el-button type="text" style="color: #F82222" @click="deleteSku(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>

    <!-- SKU编辑弹窗 -->
    <el-dialog
        top="10vh"
        width="800px"
        title="编辑SKU"
        :visible.sync="skuDialogValue"
        :close-on-click-modal="false"
        append-to-body
    >
      <SubmitForm
          :rule-form="skuForm"
          :rules="skuRules"
          :form-list="skuFormList"
          @change="handleSkuFormChange"
          @save="onSaveSku"
          @close="skuDialogValue = false"
      />
    </el-dialog>
  </el-dialog>
</template>

<script>
import {http} from '@/api'

export default {
  name: 'SkuBatchManager',
  data() {
    return {
      dialogValue: false,
      skuDialogValue: false,
      loading: false,
      currentProduct: {},
      skuList: [],
      selectedSkus: [],
      skuForm: {},
      // 批量操作数据
      batchPrice: '',
      batchOriginalPrice: '',
      batchStock: '',
      batchUnit: '',
      batchStatus: '',
      defaultSkuForm: {
        product_id: '',
        sku_code: '',
        spec_combination: '{}',
        price: 0.00,
        original_price: 0.00,
        stock: 0,
        image: '',
        unit: '',
        status: 1
      },
      skuRules: {
        sku_code: [{required: true, message: 'SKU编码不能为空'}],
        price: [{required: true, message: '价格不能为空'}],
      },
      skuFormList: [
        {
          label: 'SKU编码',
          prop: 'sku_code',
          name: 'input',
          colSpan: 12,
          placeholder: '请输入SKU编码'
        },
        {
          label: 'SKU图片',
          prop: 'image',
          name: 'file',
          colSpan: 12
        },
        {
          label: '规格组合',
          prop: 'spec_combination',
          name: 'input',
          colSpan: 24,
          placeholder: '请输入规格组合JSON，如：{"颜色":"红色","尺寸":"L"}'
        },
        {
          label: '价格',
          prop: 'price',
          name: 'number',
          colSpan: 12,
          min: 0,
          precision: 2,
          step: 0.01
        },
        {
          label: '原价',
          prop: 'original_price',
          name: 'number',
          colSpan: 12,
          min: 0,
          precision: 2,
          step: 0.01
        },
        {
          label: '库存',
          prop: 'stock',
          name: 'number',
          colSpan: 12,
          min: 0
        },
        {
          label: '单位',
          prop: 'unit',
          name: 'input',
          colSpan: 12,
          placeholder: '如：个、件、套'
        },
        {
          label: '状态',
          prop: 'status',
          name: 'switch',
          colSpan: 24,
          activeValue: 1,
          inactiveValue: 0,
          activeText: '启用',
          inactiveText: '禁用'
        },
      ]
    }
  },
  methods: {
    open(product) {
      this.currentProduct = product;
      this.dialogValue = true;
      this.loadSkuList();
    },
    
    loadSkuList() {
      this.loading = true;
      http.productSku.list({ product_id: this.currentProduct.id }).then(res => {
        this.skuList = res.data;
        this.loading = false;
      }).catch(() => {
        this.loading = false;
      });
    },
    
    refreshList() {
      this.loadSkuList();
    },
    
    onSelectionChange(selection) {
      this.selectedSkus = selection;
    },
    
    selectAll() {
      this.$refs.skuTable.toggleAllSelection();
    },
    
    unselectAll() {
      this.$refs.skuTable.clearSelection();
    },
    
    batchUpdate() {
      if (this.selectedSkus.length === 0) {
        this.$message.warning('请选择要批量更新的SKU');
        return;
      }
      
      const updateData = {};
      if (this.batchPrice !== '') updateData.price = parseFloat(this.batchPrice);
      if (this.batchOriginalPrice !== '') updateData.original_price = parseFloat(this.batchOriginalPrice);
      if (this.batchStock !== '') updateData.stock = parseInt(this.batchStock);
      if (this.batchUnit !== '') updateData.unit = this.batchUnit;
      if (this.batchStatus !== '') updateData.status = this.batchStatus;
      
      if (Object.keys(updateData).length === 0) {
        this.$message.warning('请设置要更新的字段');
        return;
      }
      
      const promises = this.selectedSkus.map(sku => {
        return http.productSku.update(sku.id, { ...sku, ...updateData });
      });
      
      Promise.all(promises).then(() => {
        this.$message.success('批量更新成功');
        this.loadSkuList();
        // 清空批量操作数据
        this.batchPrice = '';
        this.batchOriginalPrice = '';
        this.batchStock = '';
        this.batchUnit = '';
        this.batchStatus = '';
      }).catch(() => {
        this.$message.error('批量更新失败');
      });
    },
    
    batchDelete() {
      if (this.selectedSkus.length === 0) {
        this.$message.warning('请选择要删除的SKU');
        return;
      }
      
      this.$confirm(`确定要删除选中的 ${this.selectedSkus.length} 个SKU吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const promises = this.selectedSkus.map(sku => {
          return http.productSku.delete(sku.id);
        });
        
        Promise.all(promises).then(() => {
          this.$message.success('批量删除成功');
          this.loadSkuList();
        }).catch(() => {
          this.$message.error('批量删除失败');
        });
      });
    },
    
    updateSku(sku) {
      http.productSku.update(sku.id, sku).then(() => {
        this.$message.success('更新成功');
      }).catch(() => {
        this.$message.error('更新失败');
      });
    },
    
    editSku(row) {
      this.skuForm = { ...row };
      this.skuDialogValue = true;
    },
    
    deleteSku(row) {
      this.$confirm('确定要删除这个SKU吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        http.productSku.delete(row.id).then(() => {
          this.$message.success('删除成功');
          this.loadSkuList();
        });
      });
    },
    
    handleSkuFormChange({key, val}) {
      // 处理SKU表单变化
    },
    
    onSaveSku() {
      // 验证规格组合JSON格式
      try {
        if (this.skuForm.spec_combination) {
          JSON.parse(this.skuForm.spec_combination);
        }
      } catch (e) {
        this.$message.error('规格组合JSON格式不正确');
        return;
      }
      
      http.productSku.update(this.skuForm.id, this.skuForm).then(res => {
        this.$message.success('操作成功');
        this.skuDialogValue = false;
        this.loadSkuList();
      });
    }
  }
}
</script>

<style scoped lang="scss">
.sku-batch-container {
  .product-info {
    margin-bottom: 20px;
    padding: 15px;
    background-color: #f5f7fa;
    border-radius: 4px;
    
    h3 {
      margin: 0 0 10px 0;
      color: #303133;
    }
    
    p {
      margin: 0;
      color: #606266;
    }
  }
  
  .batch-actions {
    margin-bottom: 20px;
  }
  
  .sku-list {
    .el-table {
      max-height: 500px;
      overflow-y: auto;
    }
  }
}
</style> 